<?php

// Created by Khanh Nam
class JobsController extends Controller
{

    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
            array(
                'application.filters.RequireLoginFilter',
            ),
        );
    }

    public function accessRules()
    {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions				
                'users' => array('@'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function loadModel($id)
    {
        $model = Jobs::model()->findByPk($id);
        if ($model == NULL)
        {
            throw new CHttpException(404, 'The requested page does not exist.');
        }
        return $model;
    }

    public function actionCreateDispatch($jobid)
    {
        $model = Dispatchdetails::model()->createDispatchByJob($jobid);
        if ($model != NULL)
        {
            $this->redirect(array('dispatchdetails/update', 'dispatch' => $model->dispatch));
        }
        else
        {
            throw new CHttpException('Error while create dispatch', 500);
        }
    }

    public function actionIndex($custno, $locno)
    {
        $jobs = new Jobs();
        $jobs->custno = $custno;
        $jobs->locno = $locno;
        $location = Locations::model()->find('custno=:custno AND locno=:locno', array(
            'custno' => $custno,
            'locno' => $locno
                ));
        $customer = Customers::model()->findByPk($custno);
        if ($location == NULL)
            throw new CHttpException('Your request page can not found', 404);

        //adding some javascript variable;
        //jsVariableGen('Locations', 'id', array('locname','add1','city','state'), 'locations', 'custno=:custno',array('custno'=>$custno),' | ');
        outputJsByList($jobs->getBillToList(), 'locations');

        outputJsByList(SalesDepartments::model()->getListData(), 'departments');

        outputJsByList(Employees::model()->getEmployeeList(), 'employees');
        outputJsByList(Employees::model()->getSalePersonList(), 'sale');

        outputJsByList(JobsBillingStatus::getListData(), 'billingstatus');

        outputJsByList(JobsStatus::getListData(), 'jobsstatus');

        outputJsByList(JobsClass::getList(), 'jobsclass');
        outputJsVarible($customer->salesperson, 'defaultSalesPerson');


        //get invoice 

        $this->render('index', array(
            'location' => $location,
            'jobs' => $jobs
        ));
    }

    public function actionDelete($jobid)
    {
        $model = $this->loadModel($jobid);
        $custno = $model->custno;
        $locno = $model->locno;
        $model->delete();
        $this->redirect(array('index', 'custno' => $custno, 'locno' => $locno));
    }

    public function actionUpdate($jobid)
    {


        $model = $this->loadModel($jobid);


        //get invoice belong of that job
        $invoiceList = Invoice::model()->findAll('jobnumber=:jobnumber AND invoicetype=:type', array(
            'jobnumber' => $model->jobid,
            'type' => Invoice::TYPE_INVOICE
                ));

        if ($model != NULL && isset($_POST['Jobs']))
        {
            $model->attributes = $_POST['Jobs'];
            if ($model->save())
            {
                //JobsNotes::model()->updateAll(array('status'=>1),'jobid=:id AND status=-1',array('id'=>$model->jobid));
                //JobsDocuments::model()->updateAll(array('status'=>1),'jobid=:id AND status=-1',array('id'=>$model->jobid));
                //$this->redirect(array('index','custno'=>$model->custno,'locno'=>$model->locno));
                echo true;
                Yii::app()->end();
            }

            //we call this function so we terminate app here
        }

        $list = JobsNotes::model()->findAll('jobid=:jobid', array('jobid' => $model->jobid));
        $rs = array();
        foreach ($list as $item)
        {
            $rs[] = $item->attributes;
        }
        Yii::app()->clientScript->registerScript('jobnotedata', "var jobsnote=" . json_encode($rs), CClientScript::POS_HEAD);
        $this->render('update', array('model' => $model));
    }

    public function actionCreate()
    {
        $job = new Jobs;
        if (isset($_POST))
        {

            $job->attributes = $_POST;
            $job->jobstatus = 8;
            $job->status = -1;
            if ($job->save())
            {
                echo json_encode(array(
                    'success' => true,
                    'msg' => "Saving successful",
                    'jobid' => $job->jobid
                ));
            }
            else
            {
                echo json_encode(array(
                    'success' => false,
                    'errors' => $job->getErrors()
                ));
            }
        }

        Yii::app()->end();
    }

    protected function performAjaxValidation($model)
    {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'jobs-form')
        {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    public function actionCancel($jobid)
    {
        $model = Jobs::model()->findByPk($jobid);
        $this->redirect(array('index', 'custno' => $model->custno, 'locno' => $model->locno));
    }

    public function actionList($custno, $locno, $page=0, $sort=NULL)
    {
        if ($page > 0)
            $page--;
        $order = CJSON::decode($sort);

        $data = new CActiveDataProvider('Jobs', array(
                    'criteria' => array(
                        'condition' => 'custno=:custno AND locno=:locno',
                        'params' => array(
                            'custno' => $custno,
                            'locno' => $locno,
                        ),
                        'order' => isset($order) ? $order[0]['property'] . ' ' . $order[0]['direction'] : NULL
                    ),
                    'pagination' => array(
                        'pageSize' => 20,
                        'currentPage' => $page
                    )
                ));

        if ($data != NULL && count($data->getData()) > 0)
        {
            $rs = array();
            $rs['totalCount'] = $data->getTotalItemCount();
            foreach ($data->getData() as $i => $item)
            {

                $rs['data'][$i] = $item->getAttributes();
                $rs['data'][$i]['locname'] = $item->location->locname;
                $rs['data'][$i]['billingstatustext'] = JobsBillingStatus::getText($item->billingstatus);
                $rs['data'][$i]['jobstatustext'] = JobsStatus::getText($item->jobstatus);
            }
            echo json_encode($rs);
        }
        Yii::app()->end();
    }

    public function actionGetLocation($locid)
    {
        $location = Locations::model()->findByPk($locid);
        if ($location != NULL)
            echo json_encode($location->getAttributes());
        Yii::app()->end();
    }

    public function actionPageList()
    {
        $this->render('pagelist');
    }

    public function getListAllData($page=NULL, $custno=null, $sort=NULL, $query=NULL, $status=NULL)
    {

        $order = CJSON::decode($sort);
        $crit = new CDbCriteria();
        if ($sort != NULL)
        {
            $crit->order = $order[0]['property'] . ' ' . $order[0]['direction'];
        }
        else
        {
            $crit->order = 'CAST( SUBSTR( jobid, 1,LOCATE(  "-", jobid )-1  ) AS SIGNED) ,CAST( SUBSTR( jobid, LOCATE(  "-", jobid ) +1 ) AS SIGNED )';
        }
        $crit->alias = 'j';
        if ($query != NULL)
        {

            $crit->join = 'left join tbl_locations l on l.locno = j.locno and l.custno = j.custno
                        left join tbl_jobs_status s on s.id = j.jobstatus
                        left join tbl_jobs_billing_status b on b.id = j.billingstatus
                ';
            $crit->condition = '
                (j.jobid =:query or 
                j.description like :like or 
                s.description like :like or 
                b.description like :like or 
                l.add1 like :like
                l.locno = :query)';
            $crit->params = array(
                'query' => $query,
                'like' => "%$query%"
            );
        }
        if ($custno != NULL)
        {
            $crit->addCondition('j.custno=:custno');
            $crit->params['custno'] = $custno;
        }
		// echo $status;
		if ($status != NULL)
        {
            $crit->addCondition('j.jobstatus=:status');
            $crit->params['status'] = $status;
        }

        $pagination = new CPagination();
        if ($page > 0)
            $page--;
        if ($page >= 0)
        {

            $pagination->setPageSize(20);

            $pagination->setCurrentPage($page);
        }
        else
        {
            $pagination->setPageSize(999999999);

            $pagination->setCurrentPage($page);
        }

        $data = new CActiveDataProvider('Jobs', array(
                    'criteria' => $crit,
                    'pagination' => $pagination
                ));
        $rs = array();
        if ($data != NULL && count($data->getData()) > 0)
        {

            $rs['totalCount'] = $data->getTotalItemCount();
            foreach ($data->getData() as $i => $item)
            {

                $rs['data'][$i] = $item->getAttributes();
                $location = $item->location;
                if ($location != NULL)
                {
                    $rs['data'][$i]['locno'] = $location->locno;
                    $rs['data'][$i]['add1'] = $location->add1;
                    $rs['data'][$i]['csz'] = $location->city . ' ' . $location->state . ' ' . $location->zip;
                    $rs['data'][$i]['locname'] = $location->locname;
                }
                else
                {
                    $rs['data'][$i]['locname'] = NULL;
                }

                $rs['data'][$i]['billingstatustext'] = JobsBillingStatus::getText($item->billingstatus);
                $rs['data'][$i]['jobstatustext'] = JobsStatus::getText($item->jobstatus);
            }
        }
        return $rs;
    }

    public function actionListAll($page=0, $custno=NULL, $sort=NULL, $query=NULL, $status=NULL)
    {
        echo CJSON::encode($this->getListAllData($page, $custno, $sort, $query, $status));
    }
    public function actionListInvoiceOfSalesOrder($salesOrderNumber){
        $list = Yii::app()->db->createCommand('select invoice from tbl_invoice where salesordersorg =:number')->bindValue('number',$salesOrderNumber)->queryAll();
        $rs = "";
        foreach($list as $i=>$item){
            $rs.=$item['invoice'];
            if($i<count($list)-1){
                $rs.='|';
            }
        }
        echo json_encode($rs);
    }
    public function actionApplyPayment($salesOrderNumber,$paymentId,$invoiceNumber){
        $paymentUtil = new PaymentUtil();
        $r = $paymentUtil->applySalesOrderPaymentToInvoice($salesOrderNumber, $paymentId,$invoiceNumber);
        if($r){
            $this->showAjaxMessage('Apply successful',true);
        }else{
            $this->showAjaxMessage('Error while apply payment, please try again later',false);
        }
    }
    
    public function actionListJobByLocation($custno,$locno){
        $jobList = Jobs::model()->findAll('custno=:custno and locno=:locno',array(
            'custno'=>$custno,
            'locno'=>$locno
        ));
        $result = array();
        foreach($jobList as $job){
            $result[] = $job->attributes;
        }
        $this->showAjaxMessage(array('list'=>$result),true);
    }
}

?>
